package com.example.a13001.shoppingmalltemplate.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/25.
 */

public class HttpUtils {
    //通用返回类
    public static class ReMessage{
        //返回状态
        private int strStatus=0;
        public void setStatus(int Status){
            this.strStatus=Status;
        }
        public int getStatus(){
            return this.strStatus;
        }
        //返回内容
        private String strContent="";
        public void setContent(String Content){
            this.strContent=Content;
        }
        public String getContent(){
            return this.strContent;
        }
    }
    //GET方式发送数据并返回JSON数据
    public static ReMessage getJsonContent(String path){
        ReMessage re = new ReMessage();
        try {
            URL url=new URL(path);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            int code=connection.getResponseCode();
            if(code==connection.HTTP_OK){
                re.setStatus(1);
                re.setContent(changeInputString(connection.getInputStream()));
            } else {
                re.setStatus(0);
                re.setContent("");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
            re.setStatus(-1);
            re.setContent(e.getMessage().toString());
        }
        return re;
    }

    //POST方式发送数据并返回JSON数据
    //Map<String,String> params = new HashMap<String,String>();
    //params.put("参数", 数据);
    //String strResult=HttpUtils.submitPostData("请求网址",params);
    public static ReMessage postJsonContent(String strUrlPath, Map<String, String> params){
        ReMessage re=new ReMessage();
        byte[] data = getRequestData(params).toString().getBytes();//获得请求体
        try {
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);     //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            //获得输出流，向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            if(response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                re.setStatus(1);
                re.setContent(changeInputString(inptStream));
            } else {
                re.setStatus(0);
                re.setContent("");
            }
        }catch (IOException e) {
            // TODO: handle exception
            re.setStatus(-1);
            re.setContent(e.getMessage().toString());
        }
        return re;
    }

    //封装请求体信息
    public static StringBuffer getRequestData(Map<String, String> params) {
        StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
        try {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    //转换数据流
    private static String changeInputString(InputStream inputStream) {

        String jsonString="";
        ByteArrayOutputStream outPutStream=new ByteArrayOutputStream();
        byte[] data=new byte[1024];
        int len=0;
        try {
            while((len=inputStream.read(data))!=-1){
                outPutStream.write(data, 0, len);
            }
            jsonString=new String(outPutStream.toByteArray());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonString;
    }

    //把远程图片转换成二进制流
    public static InputStream getStreamFromURL(String imageURL) {
        InputStream in=null;
        try {
            URL url=new URL(imageURL);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            in=connection.getInputStream();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return in;

    }
}
